<?php

namespace App\Modules\LuckDraw\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UserPropModel extends Model {
    //用户的游戏资产，比如锤子，能量啥的
    protected $table = "luck_draw_user_prop";

    public static function deduct( int $luckId, int $userId, int $num) : int {
        return self::query()
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->update([
                'avail' =>DB::raw('`avail`-' . $num),
                'used' =>DB::raw('`used`+' . $num),
            ]);
    }

    public  function add(int $luckId, int $userId, int $num): bool {
        //查看行是不是存在
        $exist = self::query()
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->exists();
        //如果存在
        if ($exist) {
            $count = self::query()
                ->where('luck_id', $luckId)
                ->where('user_id', $userId)
                ->where('status', 1)
                ->where('deleted', 0)
                ->increment("avail", $num);
            return $count > 0;
        }

        //如果不存在
        $userPropModel = new UserPropModel();
        $userPropModel->luck_id = $luckId;
        $userPropModel->user_id = $userId;
        $userPropModel->avail = $num;
        $userPropModel->used = 0;
        $userPropModel->status = 1;
        $userPropModel->deleted = 0;
        return $userPropModel->save();

    }

    public function getAvail(int $luckId, int $userId) : int {
        $userPropModel = self::query()
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->first();
        return (int)$userPropModel->avail;
    }

}